<?php


namespace app\common\controller\platform;


use app\admin\service\RbacService;
use app\common\enum\MainEnum;
use app\common\exception\ParameterFailedException;
use app\common\model\UserModel;
use app\common\model\UserPlatformModel;
use app\common\service\Lang;
use app\common\validate\UsersValidate;
use think\facade\Db;

class MpMini implements PlatformInterface
{
    public static function register()
    {
        // TODO: Implement register() method.
    }

    public static function login($data)
    {
        $wxAppID     = config('main.wx.miniapp_id');
        $wxAppSecret = config('main.wx.miniapp_secret');
        $wxLoginUrl  = sprintf(config('main.wx.mini_login_url'), $wxAppID, $wxAppSecret, $data['code']);
        $result      = curl_get($wxLoginUrl);
        $wxResult    = json_decode($result, true);
        if (empty($wxResult)) {
            throw new ParameterFailedException(['msg' => '获取session_key及openID时异常，微信内部错误']);
        }
        $loginFail = array_key_exists('errcode', $wxResult);
        if ($loginFail) {
            throw new ParameterFailedException(
                [
                    'msg'  => $wxResult['errmsg'],
                    'data' => $wxResult,
                ]
            );
        }
        $openid = $wxResult['openid'];

        $decryptData = wxDecryptData($data['encryptedData'], $data['iv'], $wxResult['session_key']);
        $userModel   = UserModel::where('mobile_number', $decryptData['phoneNumber'])->find();
        if (!$userModel) {
            //不存在主账号
            $userModel                = new UserModel();
            $password                 = substr($decryptData['phoneNumber'], -6, 6);
            $cryptRes                 = cryptPassword($password);
            $userModel->mobile_number = $decryptData['purePhoneNumber'];
            $userModel->password      = $cryptRes['password'];
            $userModel->salt          = $cryptRes['salt'];
            $userModel->group_id      = MainEnum::GROUP_USER;
            $userModel->save();
        }
        //有主账号
        $platform_specific = basename(str_replace('\\', '/', get_class(new self())));
        $where             = [
            [
                'platform_specific',
                '=',
                $platform_specific,
            ],
            [
                'platform_open_id',
                '=',
                $openid,
            ],
        ];

        $userPlatformModel = (new UserPlatformModel())->getUserPlatform($where);
        if (!$userPlatformModel) {
            $userPlatformModel                    = new UserPlatformModel();
            $userPlatformModel->user_id           = $userModel->getData('id');
            $userPlatformModel->platform_specific = $platform_specific;
            $userPlatformModel->platform_open_id  = $openid;
            if (isset($wxResult['unionid'])) {
                $userPlatformModel->platform_union_id = $wxResult['unionid'];
            }
            if ($data['pid']) {
                $where  = [
                    [
                        'platform_specific',
                        '=',
                        $platform_specific,
                    ],
                    [
                        'user_id',
                        '=',
                        $data['pid'],
                    ],
                ];
                $pModel = (new UserPlatformModel())->getUserPlatform($where);
                if (!$pModel) {
                    throw new ParameterFailedException(['msg' => '推荐人不存在']);
                }
                $userPlatformModel->pid           = $data['pid'];
                $userPlatformModel->bind_pid_time = NOW_TIME;
                if ($pModel->getData('pid')) {
                    $userPlatformModel->ppid           = $pModel->getData('pid');
                    $userPlatformModel->bind_ppid_time = NOW_TIME;
                }
            }
            $userPlatformModel->save();
        }
        $userPlatformModel->session_key = $wxResult['session_key'];
        $userPlatformModel->login_time  = NOW_TIME;
        $userPlatformModel->login_ip    = \request()->ip();
        $userPlatformModel->save();
        $accessToken                   = RbacService::setToken($userModel->getData('id'), $platform_specific);
        $user_info                     = $userModel->toArray();
        $user_info['userPlatformInfo'] = $userPlatformModel->toArray();

        return [
            'access_token' => $accessToken,
            'user_info'    => $user_info,
        ];
    }

    public static function loginOut($request)
    {

    }

    public static function removeToken()
    {
        // TODO: Implement removeToken() method.
    }

    public static function putMpMiniPlatformInfo(&$request, $params)
    {
        if (!$params['iv'] || !$params['encryptedData'] || !$params['userInfo'] || !$params['rawData'] || !$params['signature']) {
            vd(1);
            throw new ParameterFailedException();
        }
        //        if (sha1(
        //                json_encode($params['userInfo'], JSON_UNESCAPED_UNICODE) . $request->userPlatformModel->getData(
        //                    'session_key'
        //                )
        //            ) !== $params['signature']) {
        //            vd(2);
        //            throw new ParameterFailedException(['msg' => '校验数据失败']);
        //        }
        //        vd($params['userInfo'],json_decode($params['rawData'],true));
        //        if ($params['userInfo'] !== json_decode($params['rawData'],true)) {
        //            vd(3);
        //            throw new ParameterFailedException(['msg' => '校验数据失败']);
        //        }
        $userInfo                               = $params['userInfo'];
        $request->userPlatformModel->nickname   = $userInfo['nickName'];
        $request->userPlatformModel->sex        = $userInfo['gender'];
        $request->userPlatformModel->language   = $userInfo['language'];
        $request->userPlatformModel->city       = $userInfo['city'];
        $request->userPlatformModel->province   = $userInfo['province'];
        $request->userPlatformModel->country    = $userInfo['country'];
        $request->userPlatformModel->avatar_url = $userInfo['avatarUrl'];
        $request->userPlatformModel->save();
        if (!$request->userModel->getData('nickname')) {
            $request->userModel->nickname = $userInfo['nickName'];
        }
        if (!$request->userModel->getData('avatar_url')) {
            $request->userModel->avatar_url = $userInfo['avatarUrl'];
        }
        $request->userModel->save();
    }
}